﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Xml;
using aejw.Network;

namespace NetDriveMapper
{
    public partial class frm_Main : Form
    {
        private const string DEFAULT_FILENAME = "netdrivemapper.xml";
        
        public frm_Main()
        {
            InitializeComponent();
        }

        private void gw_dati_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridViewRow row = ((DataGridView)sender).Rows[e.RowIndex];
            txt_user.Text       = row.Cells["user"].Value.ToString();
            txt_password.Text = Crypt.decripta(row.Cells["pass"].Value.ToString());
            txt_letter.Text     = row.Cells["letter"].Value.ToString();
            txt_path.Text       = row.Cells["Path"].Value.ToString();
            txt_descr.Text      = row.Cells["Descrizione"].Value.ToString();
        }


        private void Mapdrive(DataGridViewRow row)
        {
            NetworkDrive oNetDrive = new NetworkDrive();
            zUpdateStatus("Mapping drive...");
            try
            {
                //set propertys
                oNetDrive.Force = this.conForce.Checked;
                oNetDrive.Persistent = this.conPersistant.Checked;
                oNetDrive.LocalDrive = row.Cells["letter"].Value.ToString();
                oNetDrive.PromptForCredentials = conPromptForCred.Checked;
                oNetDrive.ShareName = row.Cells["Path"].Value.ToString();
                oNetDrive.SaveCredentials = conSaveCred.Checked;
              
                if ( string.IsNullOrEmpty(row.Cells["user"].Value.ToString()) && 
                     string.IsNullOrEmpty(row.Cells["pass"].Value.ToString()) )
                {
                    oNetDrive.MapDrive();
                }
                else if ( string.IsNullOrEmpty(row.Cells["pass"].Value.ToString()) )
                {
                    oNetDrive.MapDrive(row.Cells["user"].Value.ToString());
                }
                else
                {
                    oNetDrive.MapDrive(row.Cells["user"].Value.ToString(), (Crypt.decripta(row.Cells["pass"].Value.ToString())));
                }
                //update status
                zUpdateStatus("Unità connessa!");
                row.Cells["status"].Value = Properties.Resources.green;
                row.Cells["Connesso_YN"].Value = "Y";
            }
            catch (Exception err)
            {
                //report error
                zUpdateStatus("Impossibile connettere l'unità! - " + err.Message);
                MessageBox.Show(this, "Impossibile connettere l'unità!\nErrore: " + err.Message,"NetDriveMapper",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
            oNetDrive = null;
        }

        private void zUpdateStatus(string psStatus)
        {
            //update the status bar and refresh
            this.conStatusBar.Panels[0].Text = psStatus;
            this.Refresh();
        }

        private void UnMapdrive(DataGridViewRow row)
        {
            NetworkDrive oNetDrive = new NetworkDrive();
            zUpdateStatus("Unmapping drive...");
            try
            {
                //unmap the drive
                oNetDrive.Force = conForce.Checked;
                oNetDrive.LocalDrive = (string)row.Cells["path"].Value;
                oNetDrive.Persistent = this.conPersistant.Checked;
                oNetDrive.UnMapDrive();
                //update status
                zUpdateStatus("Drive unmap successful");
                row.Cells["status"].Value = Properties.Resources.red;
                row.Cells["Connesso_YN"].Value = "N";
            }
            catch (Exception err)
            {
                //report error
                zUpdateStatus("Cannot unmap drive! - " + err.Message);
                MessageBox.Show(this, "Cannot unmap drive!\nError: " + err.Message, "NetDriveMapper", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            oNetDrive = null;
        }


        private void esciToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_map_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in gw_dati.Rows)
            {
                if (Convert.ToBoolean(row.Cells["checkbox"].Value))
                {
                    Mapdrive(row);

                }
            }
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if (!txt_path.Text.StartsWith("\\"))
            {
                MessageBox.Show("Inserire un percorso di rete valido", "NetDriveMapper", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(gw_dati);
                row.Cells[1].Value = Properties.Resources.red;
                row.Cells[2].Value = "N";
                row.Cells[3].Value = txt_user.Text;
                row.Cells[4].Value = (string.IsNullOrEmpty(txt_password.Text) ? "" : Crypt.cripta(txt_password.Text));
                row.Cells[5].Value = txt_letter.Text;
                row.Cells[6].Value = txt_path.Text;
                row.Cells[7].Value = txt_descr.Text;
                row.Cells[8].Value = "Apri in explorer";
                gw_dati.Rows.Add(row);
            }
            txt_user.Text = "";
            txt_password.Text = "";
            txt_letter.Text = "";
            txt_path.Text = "";
            txt_descr.Text = "";
        }

        private void btn_remove_Click(object sender, EventArgs e)
        {
            //foreach (DataGridViewRow row in gw_dati.Rows)
            for (int i = gw_dati.Rows.Count - 1; i >= 0; i--)
            {
                DataGridViewRow row = gw_dati.Rows[i];
                if (Convert.ToBoolean(row.Cells["checkbox"].Value))
                {
                    //row.Visible = false; //Remove(row);
                    gw_dati.Rows.Remove(row);
                }

            }
        }

        private void esportaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "XML file|*.xml";
            saveDialog.Title = "Save an XML File";
            saveDialog.ShowDialog();
            saveToXml(saveDialog.FileName);
        }

        /*
        private void restoreAllDriveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NetworkDrive oNetDrive = new NetworkDrive();
            try
            {
                zUpdateStatus("Restoring drive connections...");
                oNetDrive.RestoreDrives();
                //update status
                zUpdateStatus("Drive connections restore successful");
            }
            catch (Exception err)
            {
                //report error
                zUpdateStatus("Error! - " + err.Message);
                MessageBox.Show(this, "Error!\nError: " + err.Message);
            }
            oNetDrive = null;
        }
        */
        private void driveDisconnectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //show the disconnection dialog
            NetworkDrive oNetDrive = new NetworkDrive();
            oNetDrive.ShowDisconnectDialog(this);
            oNetDrive = null;
        }

        private void connectDialogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //show the connection dialog
            NetworkDrive oNetDrive = new NetworkDrive();
            oNetDrive.ShowConnectDialog(this);
            oNetDrive = null;
        }

        private void btn_unmap_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in gw_dati.Rows)
            {
                if (Convert.ToBoolean(row.Cells["checkbox"].Value))
                {
                    UnMapdrive(row);

                }
            }
        }

        private void gw_dati_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if ((e.ColumnIndex == 8) && (e.RowIndex != -1))
            {
                DataGridViewRow row = ((DataGridView)sender).Rows[e.RowIndex];

                if (row.Cells["Connesso_YN"].Value.ToString().Equals("N"))
                {
                    Mapdrive(row);
                }

                if (row.Cells["Connesso_YN"].Value.ToString().Equals("Y"))
                {
                    Process.Start("explorer.exe", row.Cells["path"].Value.ToString());
                }
                
            }
        }

        private void importListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "XML file|*.xml";
            openDialog.Title = "Save an XML File";
            openDialog.ShowDialog();
            loadFromXml(openDialog.FileName);       
        }

        private void loadFromXml(string filename)
        {
            if ( filename != "")
            {
                XmlDocument xdoc = new XmlDocument();
                xdoc.Load(filename);

                XmlNodeList xlist = xdoc.SelectNodes("//export");
                foreach (XmlNode node in xlist)
                {
                    gw_dati.Rows.Add(false,
                                     Properties.Resources.red,
                                     "N",
                                     node["user"].InnerText,
                                     node["pass"].InnerText,
                                     node["letter"].InnerText,
                                     node["Path"].InnerText,
                                     node["Descrizione"].InnerText,
                                     node["vai"].InnerText);
                }
            }
        }

        private void saveToXml(string filename)
        {
            if (filename != "")
            {

                DataTable dt = new DataTable();
                dt.TableName = "export";
                foreach (DataGridViewColumn col in gw_dati.Columns)
                {
                    dt.Columns.Add(col.Name, typeof(string));
                }

                //dt.Columns.Add(gw_dati.Columns["user"].Name, typeof(string));

                foreach (DataGridViewRow gridRow in gw_dati.Rows)
                {
                    DataRow dtRow = dt.NewRow();
                    for (int i = 2; i < gw_dati.Columns.Count; i++)
                        dtRow[i] = (gridRow.Cells[i].Value == null ? DBNull.Value : gridRow.Cells[i].Value);
                    dt.Rows.Add(dtRow);
                }

                dt.WriteXml(filename);
            }
        }

        private void frm_Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            saveToXml(DEFAULT_FILENAME);
        }

        private void frm_Main_Load(object sender, EventArgs e)
        {
            try
            {
                loadFromXml(DEFAULT_FILENAME);
            }
            catch (Exception ex)
            {
            }
        }

        private void guidaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Non ancora creata :P", "NetDriveMapper", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
